package sk.stuba.fiit.clientApp.gui.handler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.ImageIcon;

import sk.stuba.fiit.clientApp.cvo.VerifyPanelDataCVO;
import sk.stuba.fiit.clientApp.gui.model.FileTableModel;
import sk.stuba.fiit.clientApp.gui.panel.BasicPanel;
import sk.stuba.fiit.clientApp.singeltons.ControllerLocatorSingelton;

public class VerifyActionListener implements ActionListener {
	private static final int PATH_FILE = 3;
	private BasicPanel panel = null;
	
	public VerifyActionListener(BasicPanel basicPanel) {
		this.panel = basicPanel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		VerifyPanelDataCVO data = new VerifyPanelDataCVO();
		data.setArchival(panel.getRdbtnFromAs().isSelected());

		FileTableModel model = (FileTableModel) panel.getTableVerify()
				.getModel();
		List<File> files = new ArrayList<File>(model.getRowCount());
		for (int i = 0; i < model.getRowCount(); i++) {
			files.add(new File((String) model.getValueAt(i, PATH_FILE)));
		}
		data.setFiles(files);
		
		if (data.isArchival()) {
			data.setPath(panel.getTfArchivalPackage().getText());
		} else {
			data.setPath(panel.getTfApplication().getText());
		}

		ControllerLocatorSingelton application = ControllerLocatorSingelton
				.getInstance();
		try{
			panel.getConsole().append(
					new Date() + "\t\tVerification signature and data integrity start");
			panel.getConsole().append("\n");
			if(application.getSignatureContreoller().verifySignature(data)){
				panel.getSymbol().setIcon(new ImageIcon("./src/main/resources/icon/ok.png"));
				panel.getStatus().setText("Signature verified successfully");
			}else{
				panel.getSymbol().setIcon(new ImageIcon("./src/main/resources/icon/problem.png"));
				panel.getStatus().setText("Signature can not be fully verified");
			}
		}catch (Exception ex){
			panel.getSymbol().setIcon(new ImageIcon("./src/main/resources/icon/notok.png"));
			panel.getStatus().setText("Signature is not corrected. Data was modify!");
			panel.getConsole().append(
					new Date() + "\t\tVerification signature and data integrity end");
			panel.getConsole().append("\n");
			ex.printStackTrace();
		}
		panel.getConsole().append(
				new Date() + "\t\tVerification signature and data integrity end");
		panel.getConsole().append("\n");

	}
}
